package me.firstapp.weixin.controller.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.mp.api.OauthApi;

import me.firstapp.common.utils.StrUtils;
import me.firstapp.common.utils.WeiXinConfig;
import me.firstapp.weixin.utils.CookieMember;
import me.firstapp.weixin.utils.CookieMemberUtils;
import me.firstapp.weixin.utils.WchatConfig;

/**
 * .htm请求 微信认证登录拦截器
 * 
 * @className WeiXinHtmOauthInterceptor
 */
public class WeiXinOauthInterceptor implements HandlerInterceptor {

	private static final Log log = LogFactory.getLog(WeiXinOauthInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// 测试用
		String agent = request.getHeader("User-Agent");
		if (agent == null) {
			agent = "";
		} else {
			agent = agent.toLowerCase();
		}
		if (agent.indexOf("micromessenger") < 0) {
			return;
		}

		// 当前请求结束后，检查该用户当前认证是否为新认证，是则将用户认证信息写入cookie
		CookieMember cookieMember = (CookieMember) request.getAttribute("cookieMember");
		CookieMemberUtils.writeCookieMemberOpenId(cookieMember, request, response);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String agent = request.getHeader("User-Agent");
		if (agent == null) {
			agent = "";
		} else {
			agent = agent.toLowerCase();
		}
		if (agent.indexOf("micromessenger") < 0) {
			return false;
		} else {
			String openid = (String) request.getSession().getAttribute("openId");
			if (StrUtils.isNULL(openid)) {
				response.sendRedirect(getOauthUrl(request));
				return false;
			}
			return true;
		}

	}

	/**
	 * 获取认证URL
	 * 
	 * @param request
	 * @return
	 */
	private String getOauthUrl(HttpServletRequest request) {
		OauthApi oauthApi = new OauthApi(WchatConfig.getInstance().getWeixinProxy().getWeixinAccount());
		System.out.println(oauthApi.getUserAuthorizationURL());
		System.out.println(oauthApi.getOpenAuthorizationURL());
		System.out.println(oauthApi.getOpenAuthorizationURL(getCurrentPath(request), "snsapi_userinfo"));
		String oauthUrl = WchatConfig.getInstance().getOauthApi().getUserAuthorizationURL(
				WeiXinConfig.WEIXIN4J_USER_OAUTH_REDIRECT_URI, getCurrentPath(request), "snsapi_userinfo");
		log.debug("[微信认证] URL : " + oauthUrl);
		System.out.println("[微信认证] URL : " + oauthUrl);
		return oauthUrl;
	}

	/**
	 * @param request
	 * @return
	 */
	private String getCurrentPath(HttpServletRequest request) {
		StringBuffer currentPath = new StringBuffer(request.getServletPath());
		if (request.getQueryString() != null) {
			// 需要从参数中把fmid及微信拼上的其他参数去掉，以免用户不停直接转发，url越来越长且fmid重复
			String queryString = request.getQueryString();
			queryString = queryString.replaceAll("&?(fmid|from|isappinstalled)=[^&]+", "");
			if (queryString.startsWith("&")) {
				queryString = queryString.substring(1);
			}
			if (StrUtils.isNotNULL(queryString)) {
				currentPath.append('?').append(queryString);
			}
		}
		return currentPath.toString();
	}

}
